#include "BlockManager.h"
#include "Exception.h"

sRow BlockManager::claimNewRow(uShort size)
{
	if (size > Block::INI_FREE_SPACE + Block::ROW_HEADER_SIZE)
		throw ERR_TO_BIG_DATA_SIZE;
	uInt bId;
    bId = 0;
	Block* b = NULL;
	byte* rh = NULL;
	sRow row;
	while (true)
	{
		if (bId >= DiscManager::getDiscSize())
		{
			b = BufferManager::pinNewBlock();
			row = b->getNewRow(size);
			b->bytes[0] = b->bytes[0] | 0x80;
			DiscManager::write(b);
			break;
		}
		else
		{
			b = BufferManager::pinBlock(bId);
			try
			{
				row = b->getNewRow(size);
				BufferManager::setModified(bId);
				break;
			}
			catch (Error)
			{
				//Todo: case ex...
				BufferManager::unpinBlock(bId++);
			}
		}
	}
	//b->print(); /////////////////TEST
	return row;
}

sRow BlockManager::getRow(sValueId vId)
{
	Block* block = BufferManager::pinBlock(vId.blockId);
	return block->getRow(vId.rowId);
}

sValueId BlockManager::bytesToValueId(const byte* bytes)
{
	return { bytesToInt3(bytes), bytesToInt2(bytes + 3) };
}